
// Definition for a binary tree node.
function TreeNode(val, left, right) {
    this.val = (val===undefined ? 0 : val)
    this.left = (left===undefined ? null : left)
    this.right = (right===undefined ? null : right)
}


function createTree(arr) {
  let nodeArr = [];
  for(let i = 0; i < arr.length; i++) {
    let node;
    if(arr[i] == null) {
      node = null;
    } else {
      node = new TreeNode(arr[i]);
    }
    nodeArr.push(node);
  }
  for(let i = 0; i < nodeArr.length; i++) {
    if(nodeArr[i] == null) continue;
    if(2 * i + 1 < nodeArr.length) {
      nodeArr[i].left = nodeArr[2 * i + 1];
    }
    if(2 * i + 2 < nodeArr.length) {
      nodeArr[i].right = nodeArr[2 * i + 2];
    }
  }
  return nodeArr[0];
}
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumRootToLeaf = function(root) {
  if(!root) return 0;
  if(!root.left && !root.right) return root.val;
  let resultStr = [];
  function preView(node, str) {
    if(!node) return ;
    if(!node.left && !node.right) resultStr.push(str);
    if(node.left) preView(node.left, str + "" + node.left.val);
    if(node.right) preView(node.right, str + "" + node.right.val);
  }
  preView(root, root.val);

  function compute(str) {
    let sum = 0;
    for(let j = 0; j < str.length; j++) {
      sum = sum * 2 + parseInt(str[j]);
    }
    return sum;
  }
  let result = 0;
  for(let i = 0; i < resultStr.length; i++) {
    result += compute(resultStr[i]);
  }
  return result;
};

let root = [1,0,1,0,1,0,1];
console.log(sumRootToLeaf(createTree(root)));
root = [0];
console.log(sumRootToLeaf(createTree(root)));
